import React from 'react';
import { List, TextareaItem, Popup, InputItem, Checkbox } from 'antd-mobile';
import DefaultFirstPicker from 'Component/DefaultFirstPicker';
import LittleButton from 'Component/Page/CommonComponents/LittleButton';
import UploadVideo from 'Component/Page/CommonComponents/UploadVideo';
import Api from 'Utils/api';
import dialog from 'Utils/dialog';
import { CaptchaSeconds, API_HOST } from 'Constants/config';
import * as routerActions from 'react-router-redux';
import { connect } from 'react-redux';
import Recording from '../CommonComponents/Record/Recording';
import BottomButton from '../../BottomButton';
import './index.scss';

const CheckboxItem = Checkbox.CheckboxItem;

class AdvicePage extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      remainingSecond: CaptchaSeconds,
      src: '',
      title: '',
      content: '',
      suggester: '',
      id: '',
      phone: '',
      code: '',
      type: '',
      media: '',
      voiceState: '',
      messageWay: '',
      anonymous: false
    };
    this.canSendCaptcha = true;
    this.sendCaptcha = ::this.sendCaptcha;
    this.countDownSeconds = ::this.countDownSeconds;
    this.showModal = ::this.showModal;
    this.getVoiceLocalId = ::this.getVoiceLocalId;
    this.weixiJsdk = ::this.weixiJsdk;
  }
  componentDidMount() {
    this.weixiJsdk();
  }
  componentWillUnmount() {
    clearInterval(this.timer);
    this.canSendCaptcha = true;
  }
  onSubmit() {
    const {
      title, content, suggester, id, phone, code, type, messageWay, anonymous
      } = this.state;
    const self = this;
    const api = new Api({
      method: 'POST',
      path: '/suggests/user',
      data: {
        type,
        title,
        content,
        suggester,
        id_no: id,
        phone,
        code,
        media_type: messageWay,
        is_anonymity: anonymous
      },
      success: () => {
        const buttons = [
          {
            label: '知道了',
            onClick: () => { self.props.dispatch(routerActions.goBack()); },
          },
        ];
        dialog.open('提示', '提交建言成功', buttons, 'center');
        this.clear();
      },
      error: (msg) => {
        const buttons = [
          {
            label: '知道了',
            onClick: () => {},
          },
        ];
        dialog.open('提示', msg, buttons, 'center');
      }
    });
    api.run();
  }
  getVoiceLocalId(val) {
    this.setState({
      media: val,
      type: val,
    })
  }
  weixiJsdk() {
    const config = new Api({
      method: 'GET',
      path: '/wechat/config/jsapi',
      query: {
        url: encodeURIComponent(location.href.split('#')[0]),
      },
      success: (json) => {
        this.wxConfig(json);
      },
    });
    config.run();
  }
  wxConfig(json) {
    wx.config({
      debug: false,
      appId: json.app_id,
      timestamp: json.timestamp,
      nonceStr: json.nonce_str,
      signature: json.signature,
      jsApiList: [
        'uploadVoice',
        'startRecord',
        'stopRecord',
        'playVoice',
        'pauseVoice',
        'stopVoice',
        'onVoicePlayEnd',
        'uploadVoice',
      ],
    });
  }
  clear() {
    this.setState({
      src: '',
      title: '',
      content: '',
      suggester: '',
      id: '',
      phone: '',
      code: '',
      type: '',
      voiceState: '',
      messageWay: '',
      remainingSecond: 0,
    }, () => { this.upload.clearSrc() })
  }
  changeTitle(val) {
    this.setState({ title: val, });
  }
  changeContent(val) {
    this.setState({ content: val, });
  }
  changeSuggester(val) {
    this.setState({ suggester: val, });
  }
  changeId(val) {
    this.setState({ id: val, });
  }
  changePhone(val) {
    this.setState({ phone: val, });
  }
  changeCode(val) {
    this.setState({ code: val, });
  }
  changeAnonymous(e) {
    this.setState({
      anonymous: e.target.checked
    });
  }
  isok() {
    const {
      title, content, suggester, phone, code
    } = this.state;
    if (title && content && suggester &&
       phone && code) {
      return false;
    }
    return true;
  }
  showModal() {
    const { voiceState } = this.state;
    Popup.show(
      <Recording
        voiceState={voiceState}
        getVoiceLocalId={this.getVoiceLocalId}
      />
      , { animationType: 'slide-up' }
    )
  }
  changeMessage(val) {
    this.setState({
      messageWay: val[0],
    })
  }
  handleUpload(newId) {
    this.setState({
      type: newId,
    })
  }
  /**
   * 验证码倒计时
   */
  countDownSeconds() {
    const remainingSecond = this.state.remainingSecond - 1;
    if (remainingSecond < 0) {
      this.canSendCaptcha = true;
      clearInterval(this.timer);
      this.timer = undefined;
    } else {
      if (!this.timer) {
        this.timer = setInterval(this.countDownSeconds, 1000);
      }
      this.setState(preState => (Object.assign({}, preState, {
        remainingSecond,
      })));
    }
  }
  /**
   * 发送验证码
   */
  sendCaptcha() {
    const { phone } = this.state;
    if (!this.canSendCaptcha) {
      return;
    }
    this.canSendCaptcha = false;
    setTimeout(() => {
      this.setState({
        remainingSecond: CaptchaSeconds,
      }, () => {
        this.countDownSeconds();
      });
    }, 0);
    const self = this;
    const api = new Api({
      method: 'POST',
      path: '/phone/verify_code',
      data: {
        phone,
      },
      error: () => {
        self.setState({
          remainingSecond: 0,
        }, () => {
          self.canSendCaptcha = true;
          clearInterval(this.timer);
          this.timer = undefined;
        });
      },
    });
    api.run();
  }
  render() {
    const {
      title, content, suggester, id, phone, code, messageWay, remainingSecond, anonymous
    } = this.state;
    const messageDate = [
      {
        label: '视频',
        value: 'video',
      },
      {
        label: '音频',
        value: 'audio',
      },
    ]
    return (
      <div className="outer-wrap">
        <div className="advice-page">
          <div className="page-head">
            <div className="page-title">
              我要建言
            </div>
            <InputItem
              placeholder="请输入标题"
              onChange={this.changeTitle.bind(this)}
              value={title}
            >
              标题
            </InputItem>
          </div>
          <div className="word-mode">
            <div className="word-title">留言方式</div>
            <List>
              <DefaultFirstPicker
                value={[messageWay]}
                data={messageDate}
                extra="--请选择--"
                colnum={1}
                onChange={this.changeMessage.bind(this)}
                text="留言方式"
              />
            </List>
            <div className={`voice-img ${messageWay === 'audio' ? 'message-show' : 'message-hidden'}`}>
              <img onClick={this.showModal} src="./images/icons/icon_voice.png" alt="录音" />
              {this.state.media &&
              <p className="voice-ui">
                <audio src={`${API_HOST}/files/${this.state.media}`} controls="controls" className="audio-content">
                </audio>
              </p>
              }
            </div>
            <div className={`voice-img ${messageWay === 'video' ? 'message-show' : 'message-hidden'}`}>
              <UploadVideo
                ref={(ref) => { this.upload = ref; }}
                uploadHandle={this.handleUpload.bind(this)}
              />
            </div>
          </div>
          <div className="content">
            <div className="content-title">内容</div>
            <TextareaItem
              rows={5}
              count={140}
              placeholder="请输入内容"
              onChange={this.changeContent.bind(this)}
              value={content}
            />
          </div>
          <div className="detail">
            <List>
              <InputItem
                placeholder="请输入举报人姓名"
                onChange={this.changeSuggester.bind(this)}
                value={suggester}
              >
                建言人姓名
                <CheckboxItem className="anonymous-check" checked={anonymous} onChange={this.changeAnonymous.bind(this)}>
                  匿名
                </CheckboxItem>
              </InputItem>
              <InputItem
                placeholder="请输入身份证号"
                onChange={this.changeId.bind(this)}
                value={id}
              >
                身份证号码
              </InputItem>
              <InputItem
                placeholder="请输入联系电话"
                onChange={this.changePhone.bind(this)}
                value={phone}
              >
                联系电话
                <LittleButton
                  title={remainingSecond === 60 || remainingSecond === 0
                    ? '获取验证码'
                    : <span>剩余{remainingSecond}s</span>
                  }
                  width={200}
                  height={60}
                  className="little-button big-font in-input"
                  onClick={this.sendCaptcha}
                  disabled={!phone}
                />
              </InputItem>
              <InputItem
                placeholder="请输入验证码"
                onChange={this.changeCode.bind(this)}
                value={code}
              >
                验证码
              </InputItem>
            </List>
          </div>
        </div>
        <BottomButton
          okText="提交"
          okHandle={this.onSubmit.bind(this)}
          disabled={this.isok()}
        />
      </div>
    );
  }
}
function mapStateToProps(state) {
  return {
    ...state.routing,
  };
}
export default connect(mapStateToProps)(AdvicePage);
